package com.example.guethe.fireanalysisapp.present.user;

import android.app.Activity;
import android.util.Log;

import com.example.guethe.fireanalysisapp.R;
import com.example.guethe.fireanalysisapp.activities.LoginActivity;
import com.example.guethe.fireanalysisapp.data.beans.BaseResponse;
import com.example.guethe.fireanalysisapp.data.beans.User;
import com.example.guethe.fireanalysisapp.data.net.Api;
import com.example.guethe.fireanalysisapp.fragments.user.LoginFragment;
import com.example.guethe.fireanalysisapp.util.LoginHelper;
import com.example.guethe.fireanalysisapp.util.ToastHelper;

import cn.droidlover.xdroidmvp.mvp.XPresent;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.NetError;
import cn.droidlover.xdroidmvp.net.XApi;
import cn.droidlover.xdroidmvp.router.Router;

import static com.example.guethe.fireanalysisapp.util.MD5Util.getMD5;

/**
 * Created by 何建钦 on 2018/3/19.
 */

public class LoginPresenter extends XPresent<LoginFragment> {
    public void login () {
        final String username = getV().et_username.getText().toString();
        String password = getV().et_password.getText().toString();
        if (username.trim().isEmpty()) {
            ToastHelper.show("请输入用户名！");
            return;
        }
        if (password.trim().isEmpty()) {
            ToastHelper.show("请输入密码！");
            return;
        }

        final User user = new User(username,getMD5(password));
        Api.getBaseService().login(user)
                .compose(XApi.<BaseResponse<User>>getApiTransformer())
                .compose(XApi.<BaseResponse<User>>getScheduler())
                .subscribe(new ApiSubscriber<BaseResponse<User>>() {
                    @Override
                    protected void onFail(NetError error) {
                        ToastHelper.show(error.getMessage());
                    }

                    @Override
                    public void onNext(BaseResponse<User> userBaseResponse) {
                        if(userBaseResponse.code==200){
                            ToastHelper.show("登录成功");
                            user.setName(userBaseResponse.data.getName());
                            user.setAccessToken(userBaseResponse.data.getAccessToken());
                            LoginHelper.saveUser(user);
//                            getV().getActivity().setResult(Activity.RESULT_OK);
//                            getV().getActivity().finish();
                            User m=LoginHelper.getUser();
                            getV().toHomeActivity();

                        }else {
                            ToastHelper.show(userBaseResponse.getMsg());
                        }
                    }
                });
    }
}
